package com.etoak.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.etoak.common.core.constant.CommonConstant;
import com.etoak.common.core.vo.ResultVO;
import com.etoak.common.redis.RedisService;
import com.etoak.entity.CodeVo;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/code")
public class CodeController {

    // redis服务
    @Autowired
    RedisService redisService;

    // 验证码生成
    @Autowired
    DefaultKaptcha defaultKaptcha;

    @GetMapping("/getCode")
    public ResultVO<CodeVo> getCode() throws IOException {
        String text = defaultKaptcha.createText();
        // kaptchaTextArray
        String[] kaptchaTextArray = text.split(StrUtil.AT);

        // 将验证码结果写入Redis 默认五分钟有效
        String uuid = IdUtil.simpleUUID();

        String redisKey= CommonConstant.REDIS_CODE_PREFIX + uuid;
        String redisValue = kaptchaTextArray[1];
        redisService.setex(redisKey,redisValue,5, TimeUnit.MINUTES);

        // 创建验证码图片
        BufferedImage kaptchaImage = defaultKaptcha.createImage(kaptchaTextArray[0]);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(kaptchaImage,"png",outputStream);
        // 将图片转换为base64
        byte[] byteArray = outputStream.toByteArray();
        String base64 = Base64.encode(byteArray);

        String codeUrl = "data:image/png;base64," + base64;

        CodeVo codeVo = new CodeVo(codeUrl, uuid);
        return ResultVO.success(codeVo);
    }

}
